package cn.xing.modules.app.service.impl;

import cn.xing.common.exception.RRException;
import cn.xing.common.utils.PageUtils;
import cn.xing.common.utils.Query;
import cn.xing.modules.app.dao.CommentDao;
import cn.xing.modules.app.entity.CommentEntity;
import cn.xing.modules.app.entity.UserEntity;
import cn.xing.modules.app.service.CommentService;
import cn.xing.modules.app.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service("commentService")
public class CommentServiceImpl extends ServiceImpl<CommentDao, CommentEntity> implements CommentService {
    @Autowired
    private OrderService orderService;

    @Override
    public CommentEntity queryByOrderSn(String orderSn) {
        return this.baseMapper.selectOne(new QueryWrapper<CommentEntity>().eq("order_sn", orderSn));
    }

    @Override
    public List<CommentEntity> queryMyCommentPage(Long userId) {
        return this.baseMapper.queryMyCommentPage(userId);
    }

    @Override
    public PageUtils queryPage(String tag, Map<String, Object> params) {
        String key = (String) params.get("key");
        // app 评论标签

        QueryWrapper<CommentEntity> qw = new QueryWrapper<CommentEntity>()
                .orderByDesc("create_time")
                .eq(StringUtils.isNotEmpty(key), "order_sn", key)
                .or()
                .like(StringUtils.isNotEmpty(key), "content", key);
        if (StringUtils.isNotEmpty(tag)) {
            //
            switch (tag) {
                // 好评
                case "highScore":
                    qw.ge("score", 3);
                    break;

                // 差评
                case "lowScore":
                    qw.lt("score", 3);
                    break;
                // 有图
                case "hasImage":
                    qw.likeRight("img_urls", "http");
                    break;
                default:
                    break;
            }
        }
        IPage<CommentEntity> page = this.page(
                new Query<CommentEntity>().getPage(params),
                qw
        );

        return new PageUtils(page);
    }

    @Override
    public void save(UserEntity user, CommentEntity commentEntity) {

        String sensitiveName = user.getSensitiveName(user);
        commentEntity.setSensitiveUsername(sensitiveName);

        // 检查操作是否合法
        orderService.checkIllegal(commentEntity.getOrderSn(), user.getUserId());

        // 是否已经有评论
        if (queryByOrderSn(commentEntity.getOrderSn()) != null) {
            throw new RRException("该订单已评论");
        }
        this.baseMapper.insert(commentEntity);

    }


}